// component/startapply/startapply.js
import {
	getRegisterSendMsg,
	registerCustomerpost
} from '@/api/api.js'
import {
	createOrder
} from '@/api/order.js'
const moment = require('@/utils/moment.js');

moment.locale('en', {
	longDateFormat: {
		l: "YYYY-MM-DD",
	}
});

let app = getApp();
export default {
	name: 'startapply',
	data() {
		return {

			themeColor: getApp().globalData.themeColor,

			yyShow: false, // 日历控制
			chooseDate: '',
			chooseDateMessage: '',
			population: '', // 预计出行人数
			populationMessage: '',
			mobile: '',
			code: '', //验证码
			count: '获取验证码', //倒计时
			cutDown: null, // 计时器 

			showPeople: false, //职位身份,
			showPeopleItem: {},
			showPeopleIndex: 0,

			isShow: false,
			minDate: '',
			maxDate: '',
			contact: []
		}
	},
	props: {
		show: { // 开始办理视图显示
			type: Boolean,
			value: false,
		},
		bindPhoneShow: { //绑定手机视图
			type: Boolean,
			value: false,
		},
		visa: {
			type: Object,
			value: {},
		},
		docList: {
			type: Array,
			value: [],
		},
		activeDocIdx: {
			type: Number,
			value: 0,
		},
		role: {
			type: Number,
			value: 0,
		},
		companyId: {
			type: String,
			value: '',
		},
		contactList: {
			type: Array,
			value: [],
		},
		proId: {
			type: String,
			value: ""
		}
	},
	beforeMount() {
		let that = this
		setTimeout(function() {
			if (JSON.stringify(that.contact) == "[]") {
				that.addNewContact();
			}
			console.log('attached', that.contact)
		}, 1000)
	},
	methods: {
		change(e, value, index) {
			console.log(e, value, index, this.contact[index][value])
			let contact = this.contact
			contact[index][value] = e
			this.$nextTick(() => {
				this.contact = contact
				console.log(this.contact,1); // 输出的是更新后的值
			});

		},
		reNext2() {
			this.reNext()
		},

		change2() {
			console.log(this.contact)
		},

		onClose() {
			this.setData({
				isShow: false,
			});
			// this.$parent.$parent.show = false
			// this.$parent.$parent.contactList = this.contact
			this.$emit("show", false)
			this.$emit("contactList", this.contact)
		},

		chooseDateOpen() {
			this.setData({
				yyShow: true
			})
			console.log(this.yyShow)
		},
		// 日历值改变事件
		_yybindchange(e) {
			console.log(e)
			let date = moment(e.result).format('l')
			this.setData({
				chooseDate: date,
				chooseDateMessage: date ? '' : '请选择出行日期',
				yyShow: false
			})
		},


		addNewContact() {
			console.log('addNewContact', this.contact, this.docList)
			if (this.docList.length <= 0) return
			let item = {
				applicantName: '',
				identityType: this.docList[this.activeDocIdx].id,
				identity: this.docList[this.activeDocIdx].cn_name,
				docIdx: this.activeDocIdx
			}
			this.contact.unshift(item);
			this.setData({
				contact: this.contact
			})
			console.log('addNewContact', this.contact)
		},
		delContcat(idx) {
			uni.showModal({
				title: '提示',
				content: '确定删除此申请人信息？',
				confirmColor: this.themeColor,
				success: res => {
					console.log(res, idx)
					if (res.cancel) return;
					this.contact.splice(idx, 1)
					this.setData({
						contact: this.contact
					})
				}
			})
		},

		changDocNest(e) {
			let {
				type
			} = e.currentTarget.dataset
			let activeDocIdx = this.activeDocIdx
			if (type == 'last') {
				activeDocIdx -= 1
			} else {
				activeDocIdx += 1
			}
			if (activeDocIdx < 0) {
				activeDocIdx = this.docList.length - 1
			} else if (activeDocIdx > this.docList.length - 1) {
				activeDocIdx = 0
			}
			this.setData({
				activeDocIdx
			})
		},

		inputPhone(e) {
			this.setData({
				mobile: e
			})
		},
		inputCode(e) {
			this.setData({
				code: e
			})
		},
		inputPopulation(e) {
			console.log(e)
			this.setData({
				population: e
			})
		},

		// 表单输入
		inputCurrValue(index) {
			console.log(1)
			let value = this.contact[index].applicantName
			if (!value) {
				this.setData({
					[`contact[${index}].errorMessage`]: '请输入姓名',
					[`contact[${index}].applicantName`]: value,
				})
				return
			} else {
				this.setData({
					[`contact[${index}].applicantName`]: value,
					[`contact[${index}].errorMessage`]: ''
				})
			}
		},

		sendCode(e) {
			if (this.cutDown) return;
			uni.showLoading({
				mask: true
			})
			if (!this.mobile) return app.Tips({
				title: '请输入手机号!'
			})
			else if (!/^1[3456789]\d{9}$/.test(this.mobile)) return app.Tips({
				title: '请输入正确的手机号!'
			})
			let count = 59;
			getRegisterSendMsg(this.mobile).then(res => {
				app.Tips({
					title: '验证码已发送',
					icon: 'success'
				})
				this.cutDown = setInterval(() => {
					count -= 1;
					if (count < 0) {
						this.setData({
							count: '获取验证码',
							cutDown: null
						})
						clearInterval(this.cutDown)
						return;
					}
					this.setData({
						count: count
					})
				}, 1000)
			}).catch(err => {
				uni.hideLoading()
				console.log(err)
			})

		},
		bind() {
			uni.showLoading({
				mask: true,
			})
			if (!this.mobile) return app.Tips({
				title: '请输入手机号!'
			})
			if (!this.code) return app.Tips({
				title: '请输入验证码!'
			})
			registerCustomerpost({
					phone: this.mobile,
					code: this.code
				})
				.then(res => {
					uni.hideLoading()
					this.setData({
						bindPhoneShow: false,
						code: '',
					})
				}).catch(err => {
					uni.hideLoading()
					return app.Tips({
						title: err
					})
				})
		},
		// 下一步
		reNext() {
			console.log(this.contact,this.visa.showAddNew)
			let errCount = 0
			if (errCount > 0) return this.$forceUpdate();
			if (this.visa.showAddNew != 0) {
				console.log(this.contact)
				this.contact.map((val) => {
					console.log(val.applicantName)
					if (!val.applicantName) {
						val.errorMessage = "旅客姓名不能为空"
						errCount++
					} else {
						val.errorMessage = ""
					}
				})
			}
			if (errCount > 0) return this.$forceUpdate();
			if (this.visa.showAddNew == 0) {
				if (!this.population) {
					this.populationMessage = '请输入预计出行人数'
					errCount++
				} else {
					this.populationMessage = ''
				}

				let arr = [];
				let item = {
					applicantName: '待上传',
					identityType: this.docList[this.activeDocIdx].id,
					identity: this.docList[this.activeDocIdx].cn_name,
					docIdx: this.activeDocIdx,
				}
				for (let i = 0; i < this.population; i++) {
					arr.push(item);
				}
				this.setData({
					contact: arr
				})
			}

			if (errCount > 0) return this.$forceUpdate();

			uni.showLoading({
				title: '请稍后',
				mask: true
			})
			let data = {
				// plannedDepartureDate: `${this.chooseDate.year}-${this.chooseDate.month}-${this.chooseDate.day}`,
				plannedDepartureDate: this.chooseDate,
				proId: this.proId,
				mobile: this.mobile,
				applicants: this.contact,
				companyId: this.companyId,
				zfb: '1'
			}

			console.log(data, 'data')
			// 创建订单
			createOrder(data)
				.then((res) => {
					uni.hideLoading()
					// app.Tips({
					//   title: res.message,
					//   icon: 'success'
					// })
					// uni.redirectTo({
					// 	url: `/pages/visa/dataProgress?orderId=${res.data.orderId}`,
					// })
					// setTimeout(() => {
					//   uni.redirectTo({
					//     url: `/pages/dataProgress/dataProgress?orderId=${res.data.orderId}`,
					//   })
					// }, 1234)
				}).catch(err => {
					app.Tips({
						title: err
					})
					console.log('err => ', err)
				})
		},


		showPopupPeople(item, index) {
			this.setData({
				showPeople: true,
				showPeopleIndex: index,
				showPeopleItem: item
			});
		},

		onClosePeople() {
			this.setData({
				showPeople: false
			});
		},
		showPeopleChange(index) {
			let idx = this.showPeopleIndex
			this.setData({
				[`contact[${idx}].identityType`]: this.docList[index].id,
				[`contact[${idx}].identity`]: this.docList[index].cn_name,
				[`contact[${idx}].docIdx`]: index,
				showPeople: false
			})

			let contact = JSON.parse(JSON.stringify(this.contact))
			// this.contact = []
			this.contact = contact
			console.log(index, idx, this.docList[index].cn_name, this.contact)
		},

		gotoNextBack() {
			this.setData({
				mobile: '',
				code: '',
				bindPhoneShow: false
			})
		},
		calendarFormatter(day) {
			const month = day.date.getMonth() + 1;
			const date = day.date.getDate();

			if (month === 5) {
				if (date === 1) {
					day.topInfo = '劳动节';
				} else if (date === 4) {
					day.topInfo = '青年节';
				} else if (date === 11) {
					day.text = '今天';
				}
			}

			// if (day.type === 'start') {
			// 	day.bottomInfo = '入住';
			// } else if (day.type === 'end') {
			// 	day.bottomInfo = '离店';
			// }
			return day;
		},


	},
	watch: {
		show(newValue, oldValue) {
			this.isShow = newValue;
			if (this.isShow) {
				this.minDate = moment(new Date()).format('l')
				this.maxDate = moment(new Date().setFullYear(new Date(this.minDate).getFullYear() + 8)).format('l')
			}
		},
		contactList(newValue, oldValue) {
			this.contact = newValue;
		},
	}

}
